﻿using Lamex.Base;
using Lamex.Common;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mNC.UI
{
    public partial class frmNC_Issue_Register : frmBaseChild
    {
        byte[] buffer = null;
        string strSavePath = ""; //存放本地图片路径，可以全局配置
        string strFileName = "";
        string strState;//NC状态
        public frmNC_Issue_Register()
        {
            InitializeComponent();
        }
        public frmNC_Issue_Register(string PartNo)
        {
            InitializeComponent();
            txtNumber.Text = PartNo;
        }
        
        public void initPartNo(string PartNo)
        {
            txtNumber.Text = PartNo;
        }
        private void frmNC_Issue_Register_Load(object sender, EventArgs e)
        {
            base.InitButtons();
            InitInfo();
            cbMan.Enabled = false;
        }
        public void InitInfo()
        {
            //问题来源
            string IssueFrom = @"select FIELD_VALUE_OPTION from Sys_ControlValueOption where FIELD_NAME='NC_ISSUE_FROM'";
            DataTable dt_IssueFrom = BaseBuildSql.GetDataTableBySql(IssueFrom);
            if (dt_IssueFrom.Rows.Count > 0)
            {
                string[] list = dt_IssueFrom.Rows[0]["FIELD_VALUE_OPTION"].ToString().Split(',');
                foreach (var item in list)
                {
                    this.cbIssue_From.Properties.Items.Add(item);
                }
            }
            //问题类别
            string IssueType = @"select FIELD_VALUE_OPTION from Sys_ControlValueOption where FIELD_NAME='NC_ISSUE_CATEGORY'";
            DataTable dt_IssueType = BaseBuildSql.GetDataTableBySql(IssueType);
            if (dt_IssueType.Rows.Count > 0)
            {
                string[] list = dt_IssueType.Rows[0]["FIELD_VALUE_OPTION"].ToString().Split(',');
                foreach (var item in list)
                {
                    this.cbIssue_Type.Properties.Items.Add(item);
                }
            }
            //跟进部门
            string sqlDept = @"select FIELD_VALUE_OPTION from Sys_ControlValueOption where FIELD_NAME='NC_ISSUE_RESPONSIBLE_DEPT'";
            DataTable dt_Dept = BaseBuildSql.GetDataTableBySql(sqlDept);
            if (dt_Dept.Rows.Count > 0)
            {
                string[] list = dt_Dept.Rows[0]["FIELD_VALUE_OPTION"].ToString().Split(',');
                foreach (var item in list)
                {
                    this.cbDepart.Properties.Items.Add(item);
                }
            }
        }

        private void cbDepart_EditValueChanged(object sender, EventArgs e)
        {
           
        }
        private void cbDepart_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strDept = cbDepart.Text;
            if (!string.IsNullOrEmpty(strDept))
            {
                cbMan.Properties.Items.Clear();
                cbMan.Text = "";
                cbMan.Enabled = true;
                //获取跟进人             
                string strNumber = txtNumber.Text;
                strState = Common.GetDataTable.GetState(strNumber).Trim();
                DataTable dataTable = Common.GetDataTable.GetManByDept(strDept, strNumber, strState);
                if (dataTable.Rows.Count > 0)
                {
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        this.cbMan.Properties.Items.Add(dataTable.Rows[i]["NAME"].ToString());
                    }
                    cbMan.SelectedIndex = 0;
                }
            }
        }
        public override void DoSave(IButtonInfo sender)
        {
            //空检查
            string strIssueFrom = cbIssue_From.Text;
            string strIssueType = cbIssue_Type.Text;
            string strDept = cbDepart.Text;
            string strQty = txtQty.Text;
            string strDesc = txtDesc.Text;
            string strNumber = txtNumber.Text;
            string strMan = cbMan.Text;
            if (string.IsNullOrEmpty(strIssueFrom) || string.IsNullOrEmpty(strIssueType) ||
                string.IsNullOrEmpty(strDept) || string.IsNullOrEmpty(strQty) ||
                string.IsNullOrEmpty(strDesc) || string.IsNullOrEmpty(strNumber) || string.IsNullOrEmpty(strMan))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("所有信息不允许为空,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //状态检查
            strState = Common.GetDataTable.GetState(strNumber).Trim();
            if (strIssueFrom == "转码发现" || strIssueFrom == "审核发现" || strIssueFrom == "生产发现")
            {
                if ((strIssueFrom == "转码发现" && (strState == "转码中" || strState == "")) ||
                (strIssueFrom == "审核发现" && (strState == "审核中" || strState == "已转码")) ||
                (strIssueFrom == "生产发现" && strState == "已审核"))
                {
                   
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("问题来源与实际状态不符,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            try
            {
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                //using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("请稍等", "正在保存数据......", new Size(400, 80)))
                //{
                //文件移动权限检查
                string strConvertType = Common.GetDataTable.GetConvertType(strNumber);//转码类型
                if (Common.FileHelper.IsPermissionByMove(strState, strConvertType, strNumber, ""))//锁定人暂时为空
                {
                    //问题编号
                    string strSerialNo = Common.GetSerialNumber.GetSerialNo_IssueRecord();
                    Common.SerialNoHelper serialNoHelper = new Common.SerialNoHelper();
                    string strIssueNo = serialNoHelper.Generate(strSerialNo);

                    //保存数据并返回DataTable
                    DataTable dtResult = Common.SQLHelper.Insert_NC_Convert_IssueRecord(strIssueNo, strIssueFrom, strNumber, strIssueType, strDesc, strQty, strDept, strMan);
                    //问题单号写入排期表
                    // if (strIssueFrom != "图纸更改" && strDept != "NC")
                    Common.SQLHelper.Update_NC_Convert_ProcessRecord(strNumber, strIssueNo);
                    //写入历史表
                    if (strState == "已审核")
                        Common.SQLHelper.Insert_NC_Convert_ProcessRecord_History(strNumber);
                    //状态更新
                    Common.SQLHelper.Update_NC_Convert_ProcessRecordByState(strIssueFrom, strNumber);
                    //图片保存到本地，用户做保存操作时执行
                    if (buffer != null)
                    {
                        strFileName = strIssueNo + ".jpg";
                        strSavePath = @"\\TX-FS10\tx-fs1\IMA\MES\ShareResource\NC_Issue_Image\" + strFileName;
                        WriteBytesToFile(strSavePath, buffer);
                    }
                    //文件移动
                    Common.FileHelper.CopyMoveFile(strState, strConvertType, strNumber);
                    //发送邮件
                    string strAddress = Common.GetDataTable.GetEmailAddrssee(strMan);
                    if (strAddress != null)
                    {
                        string strJobName = Common.GetDataTable.GetJobName(strDept);
                        string[] strCC = Common.GetDataTable.GetEmailCC(strJobName);
                        Common.EmailHelper.SendMailUseGmail(strAddress, strCC, strSavePath, dtResult);
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("发送邮件失败,请联系管理员维护收件人邮箱地址！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    DevExpress.XtraEditors.XtraMessageBox.Show("问题登记成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //清空
                    Clear();
                }
                // }
                SplashScreenTool.CloseSplashScreen();
            }
            catch (Exception ex)
            {
                SplashScreenTool.CloseSplashScreen();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void frmNC_Issue_Register_Resize(object sender, EventArgs e)
        {
            resetPictureBox();
        }
        #region 获取图片并处理
        private void resetPictureBox()
        {
            pictureBox1.Width = panelControl2.Width - 12;
            pictureBox1.Height = panelControl2.Height - 12;
            pictureBox1.Location = new Point(6, 6);

            if (!(pictureBox1.Image == null))
            {
                if (pictureBox1.Image.Width > pictureBox1.Width || pictureBox1.Image.Height > pictureBox1.Height)
                {
                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                }
                else
                {
                    pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                }
            }
        }
        private void btnAutoPic_Click(object sender, EventArgs e)
        {
            //首先清空pictureBox1控件
            pictureBox1.Image = null;

            //获取剪贴板内容
            IDataObject iData = Clipboard.GetDataObject();

            if (iData.GetDataPresent(DataFormats.Bitmap))
            {
                //显示剪贴板图片
                Image img = (Bitmap)iData.GetData(DataFormats.Bitmap);
                pictureBox1.Image = img;
                resetPictureBox();

                buffer = PhotoImageInsert(img);            
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("剪贴板为空，或不是图片内容！", "提示", MessageBoxButtons.OK);
            }
        }
        //图片保存到本地
        public void WriteBytesToFile(string fileName, byte[] content)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter w = new BinaryWriter(fs);
            try
            {
                w.Write(content);
            }
            finally
            {
                fs.Close();
                w.Close();
            }
        }

        //把picturebox的Image 转换成二进制
        public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
        {
            //将Image转换成流数据，并保存为byte[] 
            MemoryStream mstream = new MemoryStream();
            imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length);
            mstream.Close();
            return byData;
        }

        #endregion

        private void labelGoto_Click(object sender, EventArgs e)
        {       
            DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuNC_Issue_List'");
            MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, new frmBaseChildWinForm("NC_Convert_IssueRecord", 0, true, false), dt.Rows[0]["id"].ToString());
        }
        public void Clear()
        {
            cbIssue_From.Text = "";
            txtNumber.Text = "";
            cbIssue_Type.Text = "";
            txtDesc.Text = "";
            txtQty.Text = "";
            cbDepart.Text = "";
            cbMan.Text = "";
            cbMan.Enabled = false;
            pictureBox1.Image = null;
            buffer = null;
            strSavePath = "";
            //pictureBox1.Refresh();
            //pictureBox1.Dispose();
        }
    }
}
